package com.example.composableexample.swiperefresh

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import java.time.LocalDateTime
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlin.random.Random

class SwipeRefreshViewModel : ViewModel() {

    private val _isRefreshing = MutableStateFlow(false)
    val isRefreshing = _isRefreshing.asStateFlow()

    private val _currentTime = MutableStateFlow(LocalDateTime.now())
    val currentTime = _currentTime.asStateFlow()

    private val _items = MutableStateFlow(generateItems())
    val items = _items.asStateFlow()

    private val _isLoading = MutableStateFlow(true)
    val isLoading = _isLoading.asStateFlow()


    init {
        viewModelScope.launch {
            delay(2000)
            _items.value = generateItems()
            _isLoading.value = false
        }
    }

    fun refresh() = viewModelScope.launch {
        _isRefreshing.update { true }
        delay(2000)
        _currentTime.value = LocalDateTime.now()
        _items.value = generateItems()
        _isRefreshing.update { false }
    }


    private fun generateItems(): List<RowItem> {
        val list = mutableListOf<RowItem>()
        for (i in 1 until 20) {
            list.add(
                RowItem(
                    rowImage = randomImage(),
                    number = Random.nextInt(1, 1000)
                )
            )
        }
        return list
    }

    private fun randomImage(): String {
        return "https://tse1-mm.cn.bing.net/th/id/OET.5715bf43a4c24d6c87691ebd16459e8f?w=135&h=135&c=7&rs=1&o=5&pid=1.9"
    }
}

data class RowItem(
    val rowImage: String = "",
    val number: Int = -1
)